package pacman.entries.pacman.ml.features;

import java.util.Map.Entry;
import java.util.Set;

import pacman.game.Game;
import pacman.game.Constants.GHOST;
import pacman.game.Constants.MOVE;

// returns a value between -1 and 1
// 1 means ghost is moving away from pacman
// -1 means ghost is moving towards pacman
// 0  means ghost is moving in a neutral direction, or there is no path from ghost to pacman (ghost is in the spawn area)
public class GhostDirectionFeature extends FeatureExtractor {
	private GHOST target;
	public static final float TOWARDS = 1;
	public static final float NEUTRAL_DIR = 0;
	public static final float AWAY_FROM = -1;
	public GhostDirectionFeature(float ghost) {
		target = GHOST.values()[(int)ghost];
	}
	public float Extract(Game game) {
		int pacmanNode = game.getPacmanCurrentNodeIndex();
		int ghostNode = game.getGhostCurrentNodeIndex(target);
		MOVE ghostMove = game.getGhostLastMoveMade(target);
		float f = NEUTRAL_DIR;
		

		MOVE moveAway=null;
		MOVE moveTowards=null;
		double maxDistance=Integer.MIN_VALUE;
		double minDistance=Integer.MAX_VALUE;
		
		Set<Entry<MOVE,Integer>> entrySet = game.getCurrentMaze().graph[ghostNode].neighbourhood.entrySet();
		for(Entry<MOVE,Integer> entry : entrySet)
		{
			int dist = game.getShortestPathDistance(entry.getValue(),pacmanNode);
			if(dist < minDistance) {
				minDistance = dist;
				moveTowards = entry.getKey();
			}
			if(dist > maxDistance) {
				maxDistance = dist;
				moveAway = entry.getKey();
			}
		}
		if(ghostMove == moveTowards) {
			f = TOWARDS;
		}
		else if(ghostMove == moveAway) {
			f = AWAY_FROM;
		}
		else {
			f = NEUTRAL_DIR;
		}
		
		/*
		int[] path = new int[]{};
		boolean exception = false;
		try {
			path = game.getShortestPath(pacmanNode, ghostNode);
		}
		catch (Exception e){
			exception = true;
		}
		if(!exception) {
			MOVE move = game.getGhostLastMoveMade(target);
			int newNode = game.getCurrentMaze().graph[ghostNode].neighbourhood.get(move);
			if(path.length == 0) {   // should not happen.  pacman would be eaten!
				f = NEUTRAL_DIR;
			}
			else if(path.length == 1) {   // if ghost is next to pacman
				if(newNode == pacmanNode) {  // ghost will move onto pacmans space!
					f = TOWARDS;
				}
				else if(newNode == path[0])
			}
			else if(newNode == path[1]) {
				f = 1;
			}
		}
		*/
		return f;
	}
}